package com.um.swing.dialog;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.um.swing.MainView;
import com.um.swing.bean.ImageItem;
import com.um.swing.common.util.MessageUtil;
import com.um.swing.common.util.UIUtil;
import com.um.swing.common.util.WindowUtil;
import com.um.swing.core.ImageJoinCore;
import com.um.swing.core.event.ExportEvent;
import com.um.swing.core.thread.ExportManageRunable;


import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


/**
 * 名称：导出窗口
 * 创建人：袁泉
 * 创建时间：2022年05月04日22:50:03
 */
public class JExportDialog extends JDialog {

    private static final long serialVersionUID = 2914192200129777056L;

    public static final Dimension W_SIZE = new Dimension(550, 215);

    private List<ImageItem> mList;//需要导出的数据集

    private JProgressBar jProgressBar;//进度条组件
//    private JLabel jLabel;//状态信息
    private JButton jStartBtn, jCancelBtn, jBackgroundBtn;//操作按钮
    private JTextArea jTextArea;//日志
    private JScrollBar jLogTextareaVScrollBar;//日志滚动条

    private static JExportDialog __instance = null;

    private static final String str = "加载中...";
    private static final String progressBarDefText = "准备导出";
    private int mCurrentProgress = 0;
    private boolean isExportIng = false;//是否正在导出
    private File mTargetFile;//导出到目标目录
    private ExportManageRunable mManageRunable;//导出-任务对象

    public static JExportDialog getInstance() {
        if (__instance == null)
            __instance = new JExportDialog();
        return __instance;
    }

    public boolean isExportIng() {
        return isExportIng;
    }

    private JExportDialog() {
        super(MainView.getInstance());
        UIUtil.initUI();
        this.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
        WindowUtil.setIcon(this, null);

        setPreferredSize(W_SIZE);
        setSize(W_SIZE);
        setLocationRelativeTo(null);
        setVisible(false);
        setTitle("导出暂未开始");
        jProgressBar = new JProgressBar(SwingConstants.HORIZONTAL, 0, 100);
        // 绘制百分比文本（进度条中间显示的百分数）
        Box vBox = Box.createVerticalBox();
        jProgressBar.setStringPainted(true);
        jProgressBar.setString(progressBarDefText);
        jProgressBar.setPreferredSize(new Dimension((int) W_SIZE.getWidth() - 20, 20));
        //操作按钮
        vBox.add(jProgressBar);
        //日志部分
        jTextArea = new JTextArea();
        jTextArea.setEditable(false);
        jTextArea.setFocusable(false);
        JScrollPane textAreaScroll = new JScrollPane(jTextArea);
        textAreaScroll.setPreferredSize(new Dimension(100, 100));
        textAreaScroll.setBorder(new TitledBorder("日志输出"));
        jLogTextareaVScrollBar = textAreaScroll.getVerticalScrollBar();
        vBox.add(textAreaScroll);
        //操作按钮
        JPanel optPanel = new JPanel(new BorderLayout());
        jStartBtn = new JButton("开始");
        jCancelBtn = new JButton("取消");
        jBackgroundBtn = new JButton("后台执行");
        JPanel btnWarp = new JPanel(new FlowLayout());
        btnWarp.add(jStartBtn);
        btnWarp.add(jBackgroundBtn);
        btnWarp.add(jCancelBtn);
        optPanel.add(btnWarp, BorderLayout.EAST);
        optPanel.setBorder(new EmptyBorder(10, 0, 0, 0));
        vBox.add(optPanel);

        vBox.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        this.add(vBox, BorderLayout.NORTH);
        jProgressBar.updateUI();

        bindEvent();
    }

    private void bindEvent() {
        this.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                super.windowClosing(e);
                if (isExportIng) {
                    MessageUtil.alert(__instance, "正在执行导出任务，关闭窗口后，将在后台继续为您导出");
                }
                __instance.setVisible(false);
            }
        });

        //开始按钮事件
        jStartBtn.addActionListener(t -> {
            if (isExportIng) {
                MessageUtil.alert(__instance, "已经开始导出了，请不要重复点击");
                return;
            }
            startExport();
            this.jStartBtn.setEnabled(false);
        });
        //后台执行事件
        jBackgroundBtn.addActionListener(t -> {
            if (!isExportIng) {
                startExport();
                this.jStartBtn.setEnabled(false);
            }
            __instance.setVisible(false);
        });
        //取消事件
        jCancelBtn.addActionListener(t -> {
            if (isExportIng) {
                int btn = MessageUtil.confirm(__instance, "当前正在执行导出任务，取消之后，将会中断当前导出任务");
                if (btn == 1) {
                    return;
                }
                //中断导出任务
                mManageRunable.stopExport();
                resetExport();
            }
            setVisible(false);
        });
    }

    private void resetExport() {
        isExportIng = false;
        jStartBtn.setEnabled(true);
        mCurrentProgress = 0;

    }

    public void tryStartExport(List<ImageItem> _list, File targetFile) {
        if (isExportIng) {
            setVisible(true);
            return;
        }
        this.setTitle("导出暂未开始");
        this.jProgressBar.setValue(0);
        this.jProgressBar.setString(progressBarDefText);
        this.jTextArea.setText("");

        List<ImageItem> list = new ArrayList<>();
        for (ImageItem item : _list) {
            list.add(ObjectUtil.clone(item));
        }
        mList = list;
        mTargetFile = targetFile;
        this.mCurrentProgress = 0;
        int max = list.size();
        jProgressBar.setMaximum(max);
        jProgressBar.setValue(mCurrentProgress);
        jProgressBar.updateUI();
//        startExport(targetFile, list, max);
        this.setVisible(true);
    }

    private void startExport() {
        this.isExportIng = true;
        jProgressBar.setString(progressBarDefText);
        jProgressBar.setValue(0);
        jProgressBar.updateUI();
        this.jTextArea.setText("");
        int max = jProgressBar.getMaximum();
        mManageRunable = ImageJoinCore.exportJoinResult(mTargetFile, mList, new ExportEvent() {
            @Override
            public void onItemFinish(ImageItem item, String info, Boolean isError) {
                mCurrentProgress++;
                jProgressBar.setValue(mCurrentProgress);
                jProgressBar.setString(StrUtil.format("{}/{}", mCurrentProgress, max));
                jProgressBar.updateUI();
                String msg = StrUtil.format("[{}][{}]:{}", item.getName(), !isError ? "成功" : "失败", info);
                setTitle(msg);
                String oldStr = jTextArea.getText();
                StringBuffer textSb = new StringBuffer(msg);
                if (StrUtil.isNotBlank(oldStr)) {
                    textSb.append("\n").append(oldStr);
                }
                jTextArea.setText(textSb.toString());
//                jLogTextareaVScrollBar.setValue(jLogTextareaVScrollBar.getMaximum() + 100);
                System.out.println("导出完成：" + item.getName());
            }

            @Override
            public void onAllFinish() {
                __instance.setVisible(true);
                MessageUtil.alert(__instance, "导出完成");
                setTitle("导出完成");
                isExportIng = false;
                resetExport();
                try {
                    Desktop.getDesktop().open(mTargetFile);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        });
    }
}
